// stores/useOpenIdStore.js
import { defineStore } from 'pinia';

// 定义仓库
export const useOpenIdStore = defineStore('openIdStore', {
  // 状态
  state: () => ({
    openId: null, // 初始状态为 null
  }),
  
  // 计算属性
  getters: {
    getOpenId: (state) => state.openId, // 获取 openId
  },
  
  // 动作
  actions: {
    setOpenId(openId) {
      this.openId = openId; // 设置 openId
      uni.setStorage({ // 存储到 uni.storage
        key: 'openId',
        data: { openId },
      });
    },

    loadOpenIdFromStorage() {
      uni.getStorage({ // 从 uni.storage 加载 openId
        key: 'openId',
        success: (res) => {
          if (res.data?.openId) { // 检查 openId 是否存在
            this.openId = res.data.openId;
          }
        },
        fail: () => {
          console.log('没有找到缓存的 openId');
        },
      });
    }
  }
});
